# -*- coding: utf-8 -*-

from django.db.models.signals import post_save
from django.contrib.auth import get_user_model
from django.contrib.auth.hashers import make_password, check_password

from .models import UserProfile
User = get_user_model()


def update_or_create_user_profile(sender, instance, created, **kwargs):
    user = instance
    #password = make_password(user.password)
    if created:
        print("created")
        obj = User.objects.create(username=user.username, email=user.email, password=user.password)
        UserProfile.objects.filter(username=user.username).update(user=obj)
    else:
        print("update")
        User.objects.select_for_update().filter(username__exact=user.username).update(email=user.email, password=user.password)
        #user.auth.save()

'''
def lower_username(sender, instance, created, **kwargs):
    user = instance
    if created and settings.ST_CASE_INSENSITIVE_USERNAMES:
        (User.objects
         .filter(pk=user.pk)
         .update(username=user.username.lower()))
        user.username = user.username.lower()
'''

def post_save_receivers(*args, **kwargs):
    update_or_create_user_profile(*args, **kwargs)
    #lower_username(*args, **kwargs)
   
    
#post_save.connect(post_save_receivers, sender=UserProfile, dispatch_uid=__name__)



